package webapp

import (
	"encoding/base64"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/gin-gonic/gin"
	"log"
	"math/rand"
	"strconv"
	"time"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/pkg/dingo/global"

	"yundian/internel/app/dao"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/fddextsignuser"
	"yundian/internel/app/models/smscode"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/onlinesig"
	"yundian/internel/pkg/utils"
)

func GetSmsCode(c *gin.Context) {
	param := &struct {
		Phone string `json:"phone"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	if param.Phone == "" {
		Response(c)("手机号码不能为空", CodeSuccess, false)(OK)
		return
	}

	//openId, err := helper.GetUserNameFromCtx(c)
	//if err != nil {
	//	Response(c)("请重新登录", CodeSuccess, false)(Unauthorized)
	//}

	//查询手机号是否注册
	isRegister := dao.NewUserDao().GetPhoneIsExist(param.Phone).Unwrap().(int64)
	if isRegister > 0 {
		Response(c)("该手机号已注册，请直接登录", CodeSuccess, false)(OK)
		return
	}

	//同一个用户一天只能调用10次
	timeUnix := time.Now().Unix()
	reqCount := dao.NewUserDao().GetUserSmsCodeCount(param.Phone, int(timeUnix)).Unwrap().(int64)
	if reqCount > 10 {
		Response(c)("今天请求次数上限", CodeSuccess, false)(OK)
		return
	}

	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	if code[0:1] == "0" {
		code = "8" + code[1:]
	}

	client, err := dysmsapi.NewClientWithAccessKey(global.Cfg.Ali.AccessRegionid, global.Cfg.Ali.AccessKey, global.Cfg.Ali.AccessKeySecret)

	request := dysmsapi.CreateSendSmsRequest()

	request.Method = "POST"                               // 设置请求方式
	request.Scheme = "https"                              // https | http
	request.QueryParams["PhoneNumbers"] = param.Phone     //手机号
	request.QueryParams["SignName"] = "中曼物联"              //阿里云验证过的项目名 自己设置
	request.QueryParams["TemplateCode"] = "SMS_218615274" //阿里云的短信模板号 自己设置
	request.QueryParams["TemplateParam"] = "{\"code\":" + code + "}"
	//request属性设置

	response, err := client.SendSms(request)
	if err != nil || response.Code != "OK" || response.Message != "OK" {
		Response(c)("获取短信失败", CodeSuccess, err)(OK)
		return
	}
	//入库二维码信息
	smsCodeModel := &smscode.SmsCode{}
	smsCodeModel.Code = code
	smsCodeModel.Phone = param.Phone
	//smsCodeModel.OpenId = openId
	smsCodeModel.Status = 2
	smsCodeModel.CreateAt = dingo.Time(time.Now().Unix())

	dao.NewUserDao().InsertSmsCode(smsCodeModel)

	Response(c)("获取成功", CodeSuccess, true)(OK)
	return
}

//注册操作
func RegisterUserInfo(c *gin.Context) {
	param := &struct {
		Phone  string `json:"phone"`
		Code   string `json:"code"`
		OpenId string `json:"openid"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	if param.Phone == "" || param.Code == "" || param.OpenId == "" {
		Response(c)("无效的参数", CodeInvalidParam, false)(OK)
		return
	}
	//校验验证码
	checkInt := dao.NewUserDao().GetSmsCodeInfo(param.Phone, param.Code).Unwrap().(int64)
	if checkInt <= 0 {
		Response(c)("验证码校验失败", CodeSuccess, false)(OK)
		return
	}
	isRegister := dao.NewUserDao().GetPhoneIsExist(param.Phone).Unwrap().(int64)
	if isRegister > 0 {
		Response(c)("该手机号已注册，请直接登录", CodeSuccess, false)(OK)
		return
	}

	password := utils.EncryptPassword(param.Phone)
	usersModel := &users.UserModel{}
	usersModel.Phone = param.Phone
	usersModel.ParentID = 2
	usersModel.IsAdmin = 3
	usersModel.IsPlace = 1
	usersModel.IsDraw = 2
	usersModel.IsCash = 1

	usersModel.Openid = param.OpenId
	usersModel.ProfitProportion = 70
	usersModel.RoleID = 7
	usersModel.CreateAt = dingo.Time(time.Now().Unix())
	usersModel.UserNo = helper.PrefixMerchantUserNo + time.Now().Format("20060102150405")
	usersModel.Password = password
	//插入数据
	dao.NewUserDao().InsertRegisterUser(usersModel).Unwrap()
	//修改验证码状态
	dao.NewUserDao().UpdateSmsCode(param.Phone, param.Code)

	//注册后直接登录
	var loginInfo *request.Sign
	var err error
	var customerId string

	loginInfo, err = logic.NewAuthLogic().
		UserSignLogin(param.Phone, param.Phone, param.OpenId, c.ClientIP())
	if err != nil {
		//log.Println(err.Error())
		Response(c)(err.Error(), CodeSuccess, loginInfo)(OK)
		return
	}

	//userId, err := helper.GetUserIdFromCtx(ctx)
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeSuccess, nil)(Unauthorized)
	//	return
	//}

	userInfo := memberdao.NewMemberDao().GetFddExtSignUserByOpenId(loginInfo.UserId).Unwrap().(users.UserModel)
	//有没有注册过
	fddExtSignUser, rowsAffected := memberdao.NewMemberDao().GetFddExtSignUserRows(userInfo.UserNo)
	//注册操作
	if rowsAffected <= 0 {
		fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
		openId := userInfo.UserNo

		accountType := "1"
		log.Println("法大大注册接口")
		//调用法大大注册接口
		resData := onlinesig.AccountRegister(openId, accountType)
		log.Println("注册接口返回信息", resData)
		customerId = resData["data"].(string)

		//入库操作
		fddExtSignUserModel.UserId = userInfo.ID
		fddExtSignUserModel.CreateAt = dingo.Time(time.Now().Unix())
		fddExtSignUserModel.OpenId = openId
		fddExtSignUserModel.AccountType = accountType
		fddExtSignUserModel.IsExt = 1
		fddExtSignUserModel.CustomerId = resData["data"].(string) //注册成功返回的customer_id客户编号是用户在法大大的唯一标识。
		memberdao.NewMemberDao().InsertFddExtSignUser(&fddExtSignUserModel).Unwrap()

	}

	//返回地址
	var extUrl string

	FddExtSignUserInfo := fddExtSignUser.Unwrap().(fddextsignuser.FddExtSignUser)
	//未注册需要将客户ID绑定到model中
	if rowsAffected <= 0 {
		FddExtSignUserInfo.CustomerId = customerId
	}
	//是否实名认证过
	//请求法大大获取个人实名认证地址
	if FddExtSignUserInfo.IsExt < 2 {
		GetPersonVerifyUrlModel := request.GetPersonVerifyUrl{}
		verifyData := map[string]interface{}{}
		GetPersonVerifyUrlModel.CustomerId = FddExtSignUserInfo.CustomerId               //客户编号
		GetPersonVerifyUrlModel.VerifiedWay = "4"                                        //三要素
		GetPersonVerifyUrlModel.PageModify = "1"                                         //是否允许用户页面修改
		GetPersonVerifyUrlModel.NotifyUrl = global.Cfg.Fdd.FddNotifyUrl + "getVerifyNotify"     //回调地址
		GetPersonVerifyUrlModel.ReturnUrl = "http://webapp.chinaman.ink/user/signAffirm" //同步地址
		verifyData = onlinesig.GetPersonVerifyUrl(GetPersonVerifyUrlModel)
		log.Println("实名认证", verifyData)
		data := verifyData["data"].(map[string]interface{})

		////解码
		decodeBytes, err := base64.StdEncoding.DecodeString(data["url"].(string))
		if err != nil {
			log.Fatalln(err)
		}
		extUrl = string(decodeBytes)
		fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
		fddExtSignUserModel.UserId = userInfo.ID
		fddExtSignUserModel.TransactionNo = data["transactionNo"].(string)

		memberdao.NewMemberDao().UpdateFddUserTransactionNo(&fddExtSignUserModel)
	}
	loginInfo.ExtUrl = extUrl
	loginInfo.IsExt = strconv.Itoa(int(FddExtSignUserInfo.IsExt))
	// 响应请求
	Response(c)("登录成功", CodeSuccess, loginInfo)(OK)

	return
}
